package cn.jdemo.socket.zeroCopy.sendfile;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;
import java.nio.file.Path;
import java.nio.file.Paths;

public class SocketClient {
    public static void main(String[] args) throws IOException {
        sendFile(Paths.get("D:\\zerocopy\\hello.txt"));
    }

    public static void sendFile(Path filename) throws IOException {
        long start = System.currentTimeMillis();
        //1.打开通道
        SocketChannel socketChannel=SocketChannel.open();
        //2.连接指定ip和端口号
        socketChannel.connect (new InetSocketAddress("127.0.0.1",8880));

        try (FileChannel fileChannel = FileChannel.open(filename)) {
            long size = fileChannel.size();
            fileChannel.transferTo(0,size,socketChannel);
        } catch (IOException e) {
            e.printStackTrace();
        }
        socketChannel.close();
        long end = System.currentTimeMillis();
        System.out.println("sendFile执行耗时："+(end-start));
    }
}
